<template>
  <ex-dialog width="800px" class="ex-diolog" :title="title" :visible="visible" :close-on-click-modal="false"
    @closeDialog="handleClose">
    <div class="main" v-loading="loading">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本设置" name="first">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
            <el-form-item label="用户：" prop="" required :label-width="labelWidth">
              <el-input v-model.number="phone" placeholder="请输入用户手机号" style="width:300px" maxlength="11"
                :disabled="ruleForm.name==''?false:true"></el-input>
              <el-button type="primary" size="small" style="margin-left: 20px" @click="searchCustomer"
                v-if="ruleForm.name==''">搜索</el-button>
              <el-button type="danger" size="small" style="margin-left: 20px" @click="deleteCustomer"
                v-if="ruleForm.name!=''">重新选择</el-button>
            </el-form-item>
            <el-form-item label="" prop="name" :label-width="labelWidth">
              <el-input v-model.number="ruleForm.name" placeholder="" style="width:300px" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="正文头图" prop="img" ref="imgRef">
              <ImageUploadMore :limit="1" :fileSize="20" @successImg="getImg" :value="ruleForm.img" >
              </ImageUploadMore>
            </el-form-item>
            <el-form-item label="文章分类：" prop="articleTypeId" :label-width="labelWidth">
              <el-select v-model="ruleForm.articleTypeId" placeholder="请选择文章分类" filterable style="width:300px">
                <el-option v-for="item in options" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标题：" prop="title" :label-width="labelWidth">
              <el-input v-model="ruleForm.title" placeholder="请输入" style="width:300px"></el-input>
            </el-form-item>
            <el-form-item label="排序：" prop="sort" :label-width="labelWidth">
              <el-input v-model.number="ruleForm.sort" placeholder="请输入" style="width:300px"></el-input>
            </el-form-item>
            <el-form-item label="更新时间：" prop="updateTime" :label-width="labelWidth">
              <el-date-picker v-model="ruleForm.updateTime" type="datetime" placeholder="请选择更新时间"
                format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" style="width:300px">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="文章审核状态：" prop="status">
              <el-radio-group v-model="ruleForm.status">
                <el-radio label="2">未通过</el-radio>
                <el-radio label="1">已通过</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- <el-form-item label="图片状态：" prop="status" :label-width="labelWidth">
          <el-switch v-model="ruleForm.status" active-text="启用" inactive-text="禁用" active-value="1" inactive-value="2">
          </el-switch>
        </el-form-item> -->
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="文章内容" name="second">
          <!-- <editor v-model="ruleForm.content" :min-height="200" placeholder="请输入通知公告正文" /> -->
          <div class="richText">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
              :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" v-model="ruleForm.content" :defaultConfig="editorConfig"
              :mode="mode" @onCreated="onCreated" @onChange="onChange" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="button_box">
      <el-button type="primary" :loading="AgreeLoading" @click="submitForm('ruleForm')" v-if="id==null">立即创建</el-button>
      <el-button type="primary" :loading="AgreeLoading" @click="editForm('ruleForm')" v-if="id!=null">保存</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </ex-dialog>
</template>
<script>
  import Loading from "@/components/Loading/index";
  // import Editor from '@/components/Editor';
  import '@wangeditor/editor/dist/css/style.css'
  import {
    Editor,
    Toolbar
  } from "@wangeditor/editor-for-vue";
  // api
  import {
    kyyArticleSelect,
    kyyArticleGetCustomer,
    addKyyArticle,
    kyyArticleGetInfo,
    editKyyArticle,
  } from "@/api/kyyOfficialWebsite";

  export default {
    components: {
      Loading,
      // Editor,
      Editor,
      Toolbar
    },
    props: {
      visible: Boolean,
      id: String,
    },
    data() {
      return {
        title: '新建文章',
        loading: false,
        activeName: 'first',
        action: process.env.VUE_APP_BASE_API + "/common/v1/upload",
        info: {},
        AgreeLoading: false, //按钮loading
        options: [],
        labelWidth: '120px',
        phone: '', //查询手机号
        ruleForm: {
          articleTypeId: "", //分类id
          customerId: '', //用户id
          name: '', //用户名称(校验用)
          title: "", //标题
          sort: '', //排序
          status: '1', //文章状态（1已通过 2未通过）
          content: '', //内容
          updateTime: '', //更新时间
          img:'', //正文头图 
        },
        rules: {
          articleTypeId: [{
            required: true,
            message: '请选择文章分类',
            trigger: 'change'
          }],
          title: [{
            required: true,
            message: "请输入标题",
            trigger: ['change', 'bulr'],
          }],
          name: [{
            required: true,
            message: "请输入手机号查找用户",
            trigger: ['change', 'bulr'],
          }],
          sort: [{
            required: true,
            type: 'number',
            message: "请输入数值",
            trigger: ['change', 'bulr'],
          }],
          status: [{
            required: true,
            message: "请选择文章状态",
            trigger: 'change',
          }],
          updateTime: [{
            required: true,
            message: "请选择更新时间",
            trigger: 'change',
          }],
          img: [{
            required: true,
            message: "请上传正文头图",
            trigger: ['change', 'bulr'],
          }],
        },
        // 富文本配置
        logoUploadUrlImg: process.env.VUE_APP_BASE_API + "/common/v1/upload", //图片接口
        videoUploadUrl: process.env.VUE_APP_BASE_API + "/common/v1/upload", //视频接口
        editor: null,
        html: "<p>hello&nbsp;world</p>",
        toolbarConfig: {
          // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
          // excludeKeys: [ /* 隐藏哪些菜单 */ ],
          excludeKeys: ['group-video']
        },
        editorConfig: {

          placeholder: "请输入内容...",
          // autoFocus: false,
          // 所有的菜单配置，都要在 MENU_CONF 属性下
          MENU_CONF: {},
        },
        mode: 'default', // or 'simple'
      };
    },
    computed: {},
    created() {
      this.getType()
      console.log(this.id)
      if (this.id != null) {
        this.title = '编辑文章'
        this.getInfo()
      }

    },
    mounted() {
      var _this = this
      // 配置上传图片
      var name = ''
      this.editorConfig.MENU_CONF['uploadImage'] = {
        server: _this.logoUploadUrlImg,
        // headers: _this.headers,
        fieldName: 'file',
        //    async customUpload(file, insertFn) {
        //        console.log(file)
        //     // file 即选中的文件
        //     // 自己实现上传，并得到图片 url alt href
        //     // 最后插入图片
        //     //   insertFn(url, alt, href)
        //     },
        onSuccess(file, res) {
          name = file.name
          // console.log(`${file.name} 上传成功`, res)
        },
        customInsert(res, insertFn) {
          console.log(res)
          insertFn(res.result.url, name, res.result.url)
        }
      }
      // 配置上传视频
      this.editorConfig.MENU_CONF['uploadVideo'] = {
        server: _this.videoUploadUrl,
        // headers: _this.headers,
        fieldName: 'file',
        maxFileSize: 500 * 1024 * 1024,
        //    async customUpload(file, insertFn) {
        //        console.log(file)
        //     // file 即选中的文件
        //     // 自己实现上传，并得到图片 url alt href
        //     // 最后插入图片
        //     //   insertFn(url, alt, href)
        //     },
        customInsert(res, insertFn) {
          // res 即服务端的返回结果
          // 从 res 中找到 url ，然后插入
          insertFn(res.result.url)
        },
      }
    },
    methods: {
      getImg(e){
        // 正文头图
        this.ruleForm.img = e
        this.$refs['imgRef'].clearValidate();
      },
      onCreated(editor) {
        this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
        console.log('this.editor', this.editor)
      },
      onChange(editor) {
        console.log("onChange", editor.getHtml()); // onChange 时获取编辑器最新内容
      },
      getEditorText() {
        const editor = this.editor;
        if (editor == null) return;

        console.log(editor.getText()); // 执行 editor API
      },
      printEditorHtml() {
        const editor = this.editor;
        if (editor == null) return;

        console.log(editor.getHtml()); // 执行 editor API
      },
      //取消
      handleClose(formName) {
        this.$emit("update:visible", false);
      },
      //搜索用户
      searchCustomer() {
        if (this.phone == '') {
          this.$message.error('请输入手机号');
          return
        }
        let data = {
          phone: this.phone
        }
        kyyArticleGetCustomer(data).then((res) => {
          this.$message.success('搜索成功');
          this.ruleForm.name = res.result.name;
          this.ruleForm.customerId = res.result.id
        });
      },
      //清除用户
      deleteCustomer() {
        this.ruleForm.name = ''
        this.ruleForm.customerId = ''
        this.phone = ''
      },
      // 获取文章分类
      getType() {
        kyyArticleSelect().then((res) => {
          this.options = res.result;
        });
      },
      getInfo() { //获取信息详情
        this.loading = true
        kyyArticleGetInfo(this.id).then((res) => {
            setTimeout(() => {
              this.loading = false
            }, 500)
            let info = res.result
            this.phone = info.customerPhone
            let data = {
              phone: this.phone
            }
            kyyArticleGetCustomer(data).then((res) => {
              this.ruleForm.name = res.result.name;
              this.ruleForm.customerId = res.result.id
            });
            this.ruleForm.articleTypeId = info.articleTypeId
            this.ruleForm.title = info.title
            this.ruleForm.status = info.status
            this.ruleForm.sort = Number(info.sort)
            this.ruleForm.content = info.content
            this.ruleForm.updateTime = info.updateTime
            this.ruleForm.img = info.img
          })
          .catch(() => {
            this.loading = false;
          });
      },
      submitForm(formName) {
        //创建确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.ruleForm.content == '') {
              this.$message.error('请填写文章内容');
              return
            }
            this.AgreeLoading = true
            var params = {
              ...this.ruleForm,
            };
            addKyyArticle(params).then((res) => {
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  this.AgreeLoading = false
                }, 500);
              })
              .catch(() => {
                this.AgreeLoading = false;
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      editForm(formName) {
        //编辑确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //   alert("submit!");editGroupon
            this.AgreeLoading = true
            var params = {
              id: this.id,
              ...this.ruleForm,
            };
            editKyyArticle(params).then((res) => {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  this.AgreeLoading = false
                }, 500);
              })
              .catch(() => {
                this.AgreeLoading = false;
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
    },
  };

</script>
<style lang="scss" scoped>
  .ex-diolog {
    ::v-deep .ex--dialog--footer {
      border: none !important;
      padding: 0 !important;
    }

    ::v-deep .ex--dialog--main {
      padding: 10px 20px !important;
    }
  }

  .main {
    padding: 20px 20px;
  }

  .from_box {
    display: flex;
    margin-bottom: 20px;
  }

  .from_box_l {
    width: 110px;
    color: #606266;
    font-size: 14px;
    font-weight: bold;
  }

  .from_box_r {
    color: #333;
    font-size: 15px;
    flex: 1;
  }

  .el_table_box {
    padding: 0 20px 40px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .el_table_box_h {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #f3f3f3;
    margin-bottom: 14px;
  }

  .el_table_box_h_title {
    border-left: 4px solid #ff9300;
    padding-left: 4px;
  }

  .carousel_box {
    width: 400px;
    margin-bottom: 20px;
  }

  .swiper_img {
    width: 100%;
    height: 100%;
  }

  .carousel_box_two {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .phone_box {
    width: 100px;
    height: 100px;
    margin: 0 10px 10px 0;
  }

  .button_box {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
  }

  ::v-deep .avatar-uploader2 .el-upload {
    width: 100% !important;
  }

  .avatar-uploader2 {
    width: 228px;
    height: 128px;
    text-align: center;
    line-height: 128px;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
  }

  .banner_img {
    width: 228px;
    height: 128px;
  }

  .richText {
    border: 1px solid #ccc;
    line-height: normal;
  }

</style>
